import React from 'react'
import Dialog from '@material-ui/core/Dialog';
import DialogContent from '@material-ui/core/DialogContent';
import DialogTitle from '@material-ui/core/DialogTitle';
import { Button, Fab, FormLabel, TextField, Tooltip, ListItem, Radio } from '@material-ui/core'
import { makeStyles } from '@material-ui/core/styles';
import { Search, Loop, Add, Delete, BorderColor, GetApp } from '@material-ui/icons';
import PubSub from 'pubsub-js'
import { refreshCache, updateType, addType, getType, delType, exportType } from '../../../api/system/dict/type'
import DialogActions from '@material-ui/core/DialogActions';
import Snackbar from '@material-ui/core/Snackbar'
import { createBrowserHistory } from "history";
import { download } from '../../../uitl/ruoyi'


const useStyles = makeStyles((theme) => ({
    root: {
        '& > *': {
            margin: theme.spacing(2),
        },
        marginTop: '10px',
    },
    //功能按钮
    left: {
        float: 'left'
    },
    right: {
        float: "right",
    },
    //新增按钮
    btnInsert: {
        minWidth: '60px',
        '&:hover': {
            backgroundColor: 'blue',
            color: 'white',
        }
    },
    //修改按钮
    btnUpdate: {
        marginLeft: '15px',
        color: 'lightgreen',
        minWidth: '60px',
        border: '1px solid lightgreen',
        '&:hover': {
            backgroundColor: 'lightgreen',
            color: 'white',
        }
    },
    //删除按钮
    btnDelete: {
        marginLeft: '15px',
        minWidth: '60px',
        '&:hover': {
            backgroundColor: 'red',
            color: 'white',
        }
    },
    //导出按钮
    btnGetApp: {
        color: 'orange',
        border: '1px solid orange',
        marginLeft: '15px',
        minWidth: '60px',
        '&:hover': {
            backgroundColor: 'orange',
            color: 'white',
        }
    },
    //隐藏搜索
    btnHide: {
        border: '1px solid lightgray',
        backgroundColor: 'white',
        color: 'lightgray',
        '&:hover': {
            backgroundColor: 'lightblue',
            border: '1px solid lightblue',
            color: 'white'
        }
    },
    //刷新按钮
    btnRefresh: {
        marginLeft: '15px',
        border: '1px solid lightgray',
        backgroundColor: 'white',
        color: 'lightgray',
        '&:hover': {
            backgroundColor: 'lightblue',
            border: '1px solid lightblue',
            color: 'white'
        }
    },
    kk: {
        color: 'green'
    }

}));

export default function Dictionary() {
    const classes = useStyles();
    const [open3, setOpen3] = React.useState(false);
    const [open, setOpen] = React.useState(false);
    const [selectedValue, setValue] = React.useState();
    const [shuzi, setshuzi] = React.useState([]);  //获取数据点击的数组 Id
    const [sanchuanddaochu, setshuchu] = React.useState(true); //删除和导出按钮能不能点击初始值
    const [xiugai, setxiugai] = React.useState(true); //修改按钮能不能点击初始值
    const [data, setdata1] = React.useState({
        // 遮罩层
        loading: true,
        // 导出遮罩层
        exportLoading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 字典表格数据
        typeList: [],
        // 默认字典类型
        defaultDictType: "",
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 状态数据字典
        statusOptions: [],
        // 日期范围
        dateRange: [],
        // 查询参数
        queryParams: {
            pageNum: 2,
            // pageSize: 10,
            dictName: undefined,
            dictType: undefined,
            status: undefined
        },
        // 表单参数
        form: {
            dictId: 1,
            dictName: undefined,
            dictType: undefined,
            status: "1",
            remark: undefined
        },
        // 表单校验
        rules: {
            dictName: [
                { required: true, message: "字典名称不能为空", trigger: "blur" }
            ],
            dictType: [
                { required: true, message: "字典类型不能为空", trigger: "blur" }
            ]
        }
    })


    React.useEffect(() => {
        const token = PubSub.subscribe('PengYe', (_, stateObj) => {
            setshuzi(stateObj.selected)
            setdata1(data => {
                let newData = { ...data }
                newData.typeList = stateObj.selected
                return newData
            })
            data.typeList = stateObj.selected
            console.log(data.typeList)
        })
        return () => {
            PubSub.unsubscribe(token)
        }
    }, [])
    React.useEffect(() => {
        if (shuzi.length == 1) {
            setshuchu(false)
            setxiugai(false)
        } else if (shuzi.length > 1) {
            setxiugai(true)
        } else {
            setshuchu(true)
            setxiugai(true)
        }
    }, [shuzi])

    //获取修改的文本框
    const handleClickOpen = () => {
        setdata1(data => {
            let newData = { ...data }
            newData.form = {}
            return newData
        })
        setOpen(true);
    };
    const handleClickOpen1 = () => {
        handleUpdate()
        setOpen(true);
    }

    const handleClose = () => {
        setOpen(false);
    };


    //刷新提示框
    const [state, setState] = React.useState({
        open: false,
        vertical: 'top',
        horizontal: 'center',
        message: ''
    });

    const { vertical, horizontal, open1, message } = state;

    const handleClick = (newState) => () => {
        refreshCache().then((data) => {
            if (data.code === 200) {
                setState({ open1: true, ...newState });
                let history = createBrowserHistory();
                history.push({
                    pathname: "/Dictionary",
                });
                history.go();
            } else {
                console.log('你失败了')
            }

        });

    };

    const handleClose1 = () => {
        setState({ ...state, open1: false });
    };




    const getValue = (mes) => {
        const newLoginForm = data.form;
        return (event) => {
            newLoginForm[mes] = event.target.value;
            setValue(event.target.value);
            setdata1({ form: newLoginForm });
        };
    }



    //删除对话框


    const handleClickOpen3 = () => {
        setOpen3(true);
    };

    const handleClose3 = () => {
        let listId = data.typeList.slice(0)
        console.log(listId)
        delType(listId)
        let history = createBrowserHistory();
        history.push({
            pathname: "/Dictionary",
        });
        history.go();
        setOpen3(false);
    };
    const handleClose4 = () => {
        setOpen3(false);
    }





    const handleUpdate = () => {
        console.log('开始获取数据啦')
        let listId = data.typeList[0];
        console.log(listId)
        getType(listId).then(response => {

            setdata1(data => {
                let newData = { ...data }
                newData.form = response.data
                return newData
            })
            console.log(data.form.dictName)
        });
    }



    //确定按钮功能
    const submitForm = (newState) => {
        if (data.form.dictId != undefined) {
            updateType(data.form).then(response => {
                let history = createBrowserHistory();
                history.push({
                    pathname: "/Dictionary",
                });
                history.go();
                console.log("修改成功");

            });
        } else {
            addType(data.form).then(response => {
                let history = createBrowserHistory();
                history.push({
                    pathname: "/Dictionary",
                });
                history.go();
                console.log('添加成功！')
            });
        }
    }

    const [xiaoxikuangneirong, setxiaoxikuangneirong] = React.useState()

    //导出
    const postdaochu = () => {
        if (window.confirm("确实全部导出吗？")) {
            console.log(data.form)
            exportType(data.form).then(
                response => {
                    console.log('成功了', response);
                    download(response.msg)
                    setxiaoxikuangneirong("导出成功！")
                },
                error => {
                    setxiaoxikuangneirong("导出失败！")
                    console.log("失败了", error)
                }
            )
        }

    };





    return (
        <div className={classes.root}>

            <div className={classes.left}>
                <Button className={classes.btnInsert} onClick={handleClickOpen} variant="outlined" color="primary">
                    <Add />新增
                </Button>
                <Dialog open={open} onClose={handleClose}>
                    <DialogTitle>添加字典类型</DialogTitle>
                    <DialogContent>
                        <ListItem>
                            <FormLabel style={{ color: 'red' }}>*</FormLabel>
                            <FormLabel style={{ color: 'black', marginRight: '15px', minWidth: '70px' }}>字典管理</FormLabel>
                            <TextField
                                style={{ minWidth: '400px' }}
                                variant='outlined'
                                placeholder='请输入字典名称'
                                size='small'
                                value={data.form.dictName}
                                onChange={getValue('dictName')}
                            ></TextField>
                        </ListItem>
                        <ListItem style={{ marginTop: '15px' }}>
                            <FormLabel style={{ color: 'red' }}>*</FormLabel>
                            <FormLabel style={{ color: 'black', marginRight: '15px', minWidth: '70px' }}>字典类型</FormLabel>
                            <TextField
                                style={{ minWidth: '400px' }}
                                variant='outlined'
                                placeholder='请输入字典类型'
                                size='small'
                                value={data.form.dictType}
                                onChange={getValue('dictType')}
                            >
                            </TextField>
                        </ListItem>
                        <ListItem>
                            <FormLabel style={{ color: 'black', marginLeft: '40px', minWidth: '40px' }}>状态</FormLabel>
                            <Radio
                                checked={selectedValue === '1'}
                                onChange={getValue('1')}
                                value="1"
                            />
                            <FormLabel>正常</FormLabel>
                            <Radio
                                checked={selectedValue === '0'}
                                onChange={getValue('0')}
                                value="0"
                            />
                            <FormLabel>停用</FormLabel>
                        </ListItem>
                        <ListItem>
                            <FormLabel style={{ color: 'black', marginLeft: '40px', minWidth: '50px' }}>备注</FormLabel>
                            <TextField
                                style={{ minWidth: '400px' }}
                                variant='outlined'
                                placeholder='请输入备注'
                                size='medium'
                                value={data.form.remark}
                                onChange={getValue('remark')}
                            ></TextField>
                        </ListItem>
                        <ListItem style={{ marginTop: '15px', marginBottom: '15px' }}>
                            <Button style={{ marginLeft: '350px' }} variant="contained" color="primary" onClick={submitForm}>
                                确定
                            </Button>
                            <Button style={{ marginLeft: '15px' }} onClick={handleClose} variant="contained" >
                                取消
                            </Button>
                        </ListItem>
                    </DialogContent>
                </Dialog>
                <Button className={classes.btnUpdate} disabled={xiugai} variant="outlined" onClick={handleClickOpen1}>
                    <BorderColor />修改
                </Button>
                <Button className={classes.btnDelete} disabled={sanchuanddaochu} variant="outlined" color="secondary" onClick={handleClickOpen3}>
                    <Delete />删除
                </Button>
                <Button className={classes.btnGetApp} variant="outlined" onClick={postdaochu}>
                    <GetApp />导出
                </Button>
                <Dialog
                    open={open3}
                    onClose={handleClose3}
                    aria-labelledby="alert-dialog-title"
                    aria-describedby="alert-dialog-description"
                >
                    <DialogTitle id="alert-dialog-title">{"提示！！"}</DialogTitle>
                    <DialogContent>
                        {/* <DialogContentText id="alert-dialog-description">
                            Let Google help apps determine location. This means sending anonymous location data to
                            Google, even when no apps are running.
                        </DialogContentText> */}
                        确认删除{shuzi}编号的{data.form.dictName}用户吗？
                    </DialogContent>
                    <DialogActions>
                        <Button onClick={handleClose3} color="primary">
                            确定
                        </Button>
                        <Button onClick={handleClose4} color="primary" autoFocus>
                            取消
                        </Button>
                    </DialogActions>
                </Dialog>
            </div>
            <div className={classes.right}>
                <Tooltip title="隐藏搜索" placement="top">
                    <Fab className={classes.btnHide} size='small' variant='circular'>
                        <Search />
                    </Fab>
                </Tooltip>
                <Tooltip title="刷新" placement="top" >
                    <Fab className={classes.btnRefresh} size='small' variant='circular' onClick={handleClick({ vertical: 'top', horizontal: 'center' })}>
                        <Loop />
                    </Fab>
                </Tooltip>
                <Snackbar
                    anchorOrigin={{ vertical, horizontal }}
                    open={open1}
                    onClose={handleClose1}
                    message={xiaoxikuangneirong}
                    key={vertical + horizontal}
                />

            </div>
        </div>
    )
}


